<template>
  <div class="component-store-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon><Shop /></el-icon>
          组件商店
        </h1>
        <p class="page-description">
          浏览和安装来自后端的动态组件。所有组件都支持动态加载和配置管理。
        </p>
      </div>
      <div class="header-actions">
        <el-button-group>
          <el-button type="primary" @click="refreshComponents" :loading="refreshing">
            <el-icon><Refresh /></el-icon>
            刷新组件
          </el-button>
          <el-button @click="showInstalledOnly = !showInstalledOnly">
            <el-icon><Filter /></el-icon>
            {{ showInstalledOnly ? '显示全部' : '仅显示已安装' }}
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索组件..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="selectedCategory"
            placeholder="按分类筛选"
            clearable
            @change="handleCategoryFilter"
            style="width: 100%"
          >
            <el-option
              v-for="category in availableCategories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="sortBy"
            placeholder="排序方式"
            style="width: 100%"
          >
            <el-option label="最新发布" value="newest" />
            <el-option label="最受欢迎" value="popular" />
            <el-option label="名称排序" value="name" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button @click="resetFilters" style="width: 100%">
            <el-icon><RefreshRight /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><Grid /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ componentStats.total }}</div>
                <div class="stat-label">总组件数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon installed">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ componentStats.installed }}</div>
                <div class="stat-label">已安装</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon loaded">
                <el-icon><Download /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ componentStats.loaded }}</div>
                <div class="stat-label">已加载</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon categories">
                <el-icon><Files /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ componentStats.categories }}</div>
                <div class="stat-label">分类数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 组件列表 -->
    <div class="components-section">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="error" class="error-container">
        <el-result
          icon="error"
          :title="error"
          sub-title="无法加载组件列表，请检查网络连接或联系管理员"
        >
          <template #extra>
            <el-button type="primary" @click="refreshComponents">
              重试
            </el-button>
          </template>
        </el-result>
      </div>
      
      <div v-else-if="filteredComponents.length === 0" class="empty-container">
        <el-empty description="没有找到符合条件的组件">
          <el-button type="primary" @click="resetFilters">
            重置筛选条件
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="components-grid">
        <el-row :gutter="20">
          <el-col 
            v-for="component in filteredComponents" 
            :key="component.id"
            :span="8"
            class="component-col"
          >
            <el-card class="component-card" :class="{ 'installed': isComponentInstalled(component.id) }">
              <div class="component-header">
                <div class="component-icon">
                  <el-icon :size="32" :color="getComponentColor(component.category)">
                    <component :is="getComponentIcon(component.category)" />
                  </el-icon>
                </div>
                <div class="component-info">
                  <h3 class="component-name">{{ component.name }}</h3>
                  <p class="component-version">v{{ component.version }}</p>
                  <el-tag 
                    :type="getComponentTagType(component.category)"
                    size="small"
                    class="component-category"
                  >
                    {{ component.category }}
                  </el-tag>
                </div>
              </div>
              
              <div class="component-body">
                <p class="component-description">{{ component.description }}</p>
                
                <div class="component-stats">
                  <div class="stat-item">
                    <el-icon><Download /></el-icon>
                    <span>{{ component.download_count || 0 }}</span>
                  </div>
                  <div class="stat-item">
                    <el-icon><Star /></el-icon>
                    <span>{{ component.rating || 0 }}</span>
                  </div>
                  <div class="stat-item">
                    <el-icon><User /></el-icon>
                    <span>{{ component.author }}</span>
                  </div>
                </div>
                
                <div class="component-actions">
                  <el-button-group style="width: 100%">
                    <el-button 
                      v-if="!isComponentInstalled(component.id)"
                      type="primary" 
                      size="small"
                      @click="installComponent(component)"
                      :loading="installingComponents[component.id]"
                      style="flex: 1"
                    >
                      <el-icon><Plus /></el-icon>
                      安装
                    </el-button>
                    <el-button 
                      v-else
                      type="success" 
                      size="small"
                      @click="uninstallComponent(component)"
                      :loading="uninstallingComponents[component.id]"
                      style="flex: 1"
                    >
                      <el-icon><Check /></el-icon>
                      已安装
                    </el-button>
                    <el-button 
                      size="small"
                      @click="showComponentDetail(component)"
                      :disabled="!isComponentInstalled(component.id)"
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 组件详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      :title="selectedComponent?.name"
      width="800px"
      top="5vh"
    >
      <div v-if="selectedComponent" class="component-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="组件名称">
            {{ selectedComponent.name }}
          </el-descriptions-item>
          <el-descriptions-item label="版本">
            v{{ selectedComponent.version }}
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            <el-tag :type="getComponentTagType(selectedComponent.category)">
              {{ selectedComponent.category }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="作者">
            {{ selectedComponent.author }}
          </el-descriptions-item>
          <el-descriptions-item label="下载次数">
            {{ selectedComponent.download_count || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-rate v-model="selectedComponent.rating" disabled />
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h4>组件描述</h4>
          <p>{{ selectedComponent.description }}</p>
        </div>

        <div v-if="selectedComponent.dependencies && selectedComponent.dependencies.length > 0" class="detail-section">
          <h4>依赖组件</h4>
          <div class="dependency-tags">
            <el-tag
              v-for="dep in selectedComponent.dependencies"
              :key="dep"
              :type="isComponentInstalled(dep) ? 'success' : 'info'"
              size="small"
            >
              {{ dep }}
            </el-tag>
          </div>
        </div>

        <div class="detail-section">
          <h4>组件配置</h4>
          <el-input
            v-model="componentConfig"
            type="textarea"
            :rows="8"
            placeholder="组件配置将在此显示"
            readonly
          />
        </div>

        <div class="detail-section">
          <h4>组件预览</h4>
          <div class="component-preview">
            <div v-if="isComponentLoaded(selectedComponent.id)" class="preview-content">
              <component 
                :is="getLoadedComponent(selectedComponent.id)"
                v-bind="getComponentConfig(selectedComponent.id)"
              />
            </div>
            <div v-else class="preview-placeholder">
              <el-empty description="组件未加载">
                <el-button 
                  type="primary" 
                  @click="loadComponentForPreview(selectedComponent.id)"
                  :loading="previewLoading"
                >
                  加载预览
                </el-button>
              </el-empty>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button 
            v-if="selectedComponent && isComponentInstalled(selectedComponent.id)"
            type="primary" 
            @click="loadComponentForPreview(selectedComponent.id)"
            :loading="previewLoading"
          >
            {{ isComponentLoaded(selectedComponent.id) ? '重新加载' : '加载组件' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 组件商店页面
 * 
 * 功能：
 * 1. 从后端获取可用的组件列表
 * 2. 提供组件的安装、卸载、预览功能
 * 3. 支持组件的搜索和筛选
 * 4. 提供组件详情查看和配置管理
 */

import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Shop, 
  Refresh, 
  Filter, 
  Search, 
  RefreshRight,
  Grid,
  Check,
  Download,
  Files,
  Plus,
  View,
  Monitor,
  Message,
  Document,
  VideoPlay,
  Star,
  User
} from '@element-plus/icons-vue'
import { useModuleStore } from '@/stores/module'
import { useModuleManager } from '@/modules/composables/useModuleManager'
import { useDynamicComponent } from '@/composables/useDynamicComponent'
import type { DynamicModule } from '@/modules/dynamic/types'

// ==================== 依赖注入 ====================
const moduleStore = useModuleStore()
const moduleManager = useModuleManager()

// ==================== 响应式状态 ====================
/** 页面状态 */
const loading = ref(false)
const error = ref<string | null>(null)
const refreshing = ref(false)

/** 搜索和筛选状态 */
const searchQuery = ref('')
const selectedCategory = ref('')
const sortBy = ref('newest')
const showInstalledOnly = ref(false)

/** 组件操作状态 */
const installingComponents = ref<Record<string, boolean>>({})
const uninstallingComponents = ref<Record<string, boolean>>({})
const previewLoading = ref(false)

/** 对话框状态 */
const showDetailDialog = ref(false)
const selectedComponent = ref<DynamicModule | null>(null)
const componentConfig = ref('{}')

// ==================== 计算属性 ====================
/** 统计信息 */
const componentStats = computed(() => {
  const total = availableComponents.value.length
  const installed = availableComponents.value.filter(c => isComponentInstalled(c.id)).length
  const loaded = availableComponents.value.filter(c => moduleManager.isModuleLoaded(c.id)).length
  const categories = new Set(availableComponents.value.map(c => c.category)).size
  
  return { total, installed, loaded, categories }
})

/** 可用分类 */
const availableCategories = computed(() => {
  const categories = new Set(availableComponents.value.map(c => c.category))
  return Array.from(categories)
})

/** 过滤后的组件列表 */
const filteredComponents = computed(() => {
  let components = [...availableComponents.value]

  // 搜索筛选
  if (searchQuery.value) {
    components = components.filter(c => 
      c.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      c.description.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  // 分类筛选
  if (selectedCategory.value) {
    components = components.filter(c => c.category === selectedCategory.value)
  }

  // 已安装筛选
  if (showInstalledOnly.value) {
    components = components.filter(c => isComponentInstalled(c.id))
  }

  // 排序
  switch (sortBy.value) {
    case 'newest':
      components.sort((a, b) => 
        new Date(b.created_at || 0).getTime() - new Date(a.created_at || 0).getTime()
      )
      break
    case 'popular':
      components.sort((a, b) => (b.download_count || 0) - (a.download_count || 0))
      break
    case 'name':
      components.sort((a, b) => a.name.localeCompare(b.name))
      break
  }

  return components
})

// ==================== 模拟数据 ====================
/** 模拟的后端组件数据 */
const availableComponents = ref<DynamicModule[]>([
  {
    id: 'calendar-module',
    name: '日历组件',
    version: '1.0.0',
    description: '一个功能完整的日历组件，支持事件管理、日程安排等功能。',
    category: 'productivity',
    author: '组件开发团队',
    entry: 'index.vue',
    permissions: [],
    dependencies: [],
    is_active: true,
    created_at: '2024-01-15T00:00:00Z',
    updated_at: '2024-01-20T00:00:00Z',
    download_count: 1250,
    rating: 4.5
  },
  {
    id: 'weather-module',
    name: '天气组件',
    version: '2.1.0',
    description: '实时天气信息展示组件，支持多城市、多天预报。',
    category: 'lifestyle',
    author: '天气团队',
    entry: 'index.vue',
    permissions: [],
    dependencies: [],
    is_active: true,
    created_at: '2024-01-10T00:00:00Z',
    updated_at: '2024-01-25T00:00:00Z',
    download_count: 890,
    rating: 4.2
  },
  {
    id: 'news-module',
    name: '新闻组件',
    version: '1.5.0',
    description: '新闻资讯展示组件，支持分类浏览、个性化推荐。',
    category: 'information',
    author: '新闻团队',
    entry: 'index.vue',
    permissions: [],
    dependencies: [],
    is_active: true,
    created_at: '2024-01-05T00:00:00Z',
    updated_at: '2024-01-22T00:00:00Z',
    download_count: 2100,
    rating: 4.7
  },
  {
    id: 'chart-module',
    name: '图表组件',
    version: '3.0.0',
    description: '数据可视化图表组件，支持多种图表类型和交互。',
    category: 'data',
    author: '图表团队',
    entry: 'index.vue',
    permissions: [],
    dependencies: [],
    is_active: true,
    created_at: '2024-01-08T00:00:00Z',
    updated_at: '2024-01-28T00:00:00Z',
    download_count: 1680,
    rating: 4.8
  },
  {
    id: 'chat-module',
    name: '聊天组件',
    version: '1.2.0',
    description: '实时聊天组件，支持群聊、私聊、文件传输等功能。',
    category: 'communication',
    author: '聊天团队',
    entry: 'index.vue',
    permissions: [],
    dependencies: [],
    is_active: true,
    created_at: '2024-01-12T00:00:00Z',
    updated_at: '2024-01-30T00:00:00Z',
    download_count: 3200,
    rating: 4.6
  },
  {
    id: 'task-module',
    name: '任务管理组件',
    version: '2.0.0',
    description: '任务管理和跟踪组件，支持看板、甘特图等视图。',
    category: 'productivity',
    author: '任务团队',
    entry: 'index.vue',
    permissions: [],
    dependencies: [],
    is_active: true,
    created_at: '2024-01-18T00:00:00Z',
    updated_at: '2024-02-01T00:00:00Z',
    download_count: 980,
    rating: 4.3
  }
])

// ==================== 生命周期钩子 ====================
/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  await initializeComponentStore()
})

// ==================== 初始化方法 ====================
/**
 * 初始化组件商店
 */
async function initializeComponentStore() {
  try {
    loading.value = true
    error.value = null
    
    // 首先初始化模块系统
    await moduleStore.initialize()
    
    // 模拟从后端获取组件列表
    await fetchComponentsFromBackend()
    
    console.log('[ComponentStore] Component store initialized successfully')
  } catch (err) {
    console.error('[ComponentStore] Failed to initialize component store:', err)
    error.value = err instanceof Error ? err.message : 'Failed to initialize component store'
    ElMessage.error('初始化组件商店失败')
  } finally {
    loading.value = false
  }
}

/**
 * 从后端获取组件列表
 */
async function fetchComponentsFromBackend() {
  try {
    // 这里模拟从后端API获取组件列表
    // 在实际项目中，您需要替换为真实的API调用
    console.log('[ComponentStore] Fetching components from backend...')
    
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟API响应
    const mockResponse = {
      success: true,
      data: availableComponents.value
    }
    
    if (mockResponse.success) {
      console.log('[ComponentStore] Components fetched successfully:', mockResponse.data.length)
    } else {
      throw new Error('Failed to fetch components from backend')
    }
  } catch (err) {
    console.error('[ComponentStore] Failed to fetch components:', err)
    throw err
  }
}

// ==================== 组件操作方法 ====================
/**
 * 检查组件是否已安装
 */
function isComponentInstalled(componentId: string): boolean {
  return moduleStore.getModule(componentId) !== undefined
}

/**
 * 检查组件是否已加载
 */
function isComponentLoaded(componentId: string): boolean {
  return moduleManager.isModuleLoaded(componentId)
}

/**
 * 获取已加载的组件
 */
function getLoadedComponent(componentId: string): any {
  return moduleManager.getModuleState(componentId)?.component
}

/**
 * 获取组件配置
 */
function getComponentConfig(componentId: string): any {
  return moduleStore.getModuleConfig(componentId)
}

/**
 * 安装组件
 */
async function installComponent(component: DynamicModule) {
  try {
    installingComponents.value[component.id] = true
    
    // 注册模块到系统
    await moduleManager.registerModule(component)
    
    ElMessage.success(`组件 ${component.name} 安装成功`)
    console.log(`[ComponentStore] Component ${component.name} installed successfully`)
  } catch (err) {
    console.error('[ComponentStore] Failed to install component:', err)
    ElMessage.error(`安装组件失败: ${err instanceof Error ? err.message : 'Unknown error'}`)
  } finally {
    installingComponents.value[component.id] = false
  }
}

/**
 * 卸载组件
 */
async function uninstallComponent(component: DynamicModule) {
  try {
    uninstallingComponents.value[component.id] = true
    
    // 先卸载组件（如果已加载）
    if (isComponentLoaded(component.id)) {
      await moduleManager.unloadModule(component.id)
    }
    
    ElMessage.success(`组件 ${component.name} 卸载成功`)
    console.log(`[ComponentStore] Component ${component.name} uninstalled successfully`)
  } catch (err) {
    console.error('[ComponentStore] Failed to uninstall component:', err)
    ElMessage.error(`卸载组件失败: ${err instanceof Error ? err.message : 'Unknown error'}`)
  } finally {
    uninstallingComponents.value[component.id] = false
  }
}

/**
 * 加载组件用于预览
 */
async function loadComponentForPreview(componentId: string) {
  try {
    previewLoading.value = true
    
    // 使用动态组件composable加载组件
    const { loadComponent } = useDynamicComponent(componentId, {
      autoLoad: false,
      onLoaded: (moduleId: string) => {
        console.log(`[ComponentStore] Component ${moduleId} loaded for preview`)
        ElMessage.success('组件加载成功')
      },
      onError: (error: Error) => {
        console.error('[ComponentStore] Failed to load component for preview:', error)
        ElMessage.error(`加载组件失败: ${error.message}`)
      }
    })
    
    await loadComponent()
    
    // 更新组件配置显示
    const config = moduleStore.getModuleConfig(componentId)
    componentConfig.value = JSON.stringify(config, null, 2)
  } catch (err) {
    console.error('[ComponentStore] Failed to load component for preview:', err)
    ElMessage.error('加载组件预览失败')
  } finally {
    previewLoading.value = false
  }
}

// ==================== UI 交互方法 ====================
/**
 * 刷新组件列表
 */
async function refreshComponents() {
  try {
    refreshing.value = true
    await fetchComponentsFromBackend()
    ElMessage.success('组件列表已刷新')
  } catch (err) {
    console.error('[ComponentStore] Failed to refresh components:', err)
    ElMessage.error('刷新组件列表失败')
  } finally {
    refreshing.value = false
  }
}

/**
 * 处理搜索
 */
function handleSearch() {
  // 搜索是响应式的，不需要额外处理
}

/**
 * 处理分类筛选
 */
function handleCategoryFilter() {
  // 筛选是响应式的，不需要额外处理
}

/**
 * 重置筛选条件
 */
function resetFilters() {
  searchQuery.value = ''
  selectedCategory.value = ''
  sortBy.value = 'newest'
  showInstalledOnly.value = false
}

/**
 * 显示组件详情
 */
function showComponentDetail(component: DynamicModule) {
  selectedComponent.value = component
  componentConfig.value = JSON.stringify(getComponentConfig(component.id) || {}, null, 2)
  showDetailDialog.value = true
}

// ==================== 辅助方法 ====================
/**
 * 根据组件分类获取对应的图标
 */
function getComponentIcon(category?: string): any {
  const iconMap: Record<string, any> = {
    'default': Grid,
    'productivity': Monitor,
    'lifestyle': Sunny,
    'information': Document,
    'data': VideoPlay,
    'communication': Message,
    'task': Check
  }
  return iconMap[category || 'default'] || Grid
}

/**
 * 根据组件分类获取对应的颜色
 */
function getComponentColor(category?: string): string {
  const colorMap: Record<string, string> = {
    'default': '#409EFF',
    'productivity': '#67C23A',
    'lifestyle': '#E6A23C',
    'information': '#909399',
    'data': '#F56C6C',
    'communication': '#8B5CF6',
    'task': '#FF6B6B'
  }
  return colorMap[category || 'default'] || '#409EFF'
}

/**
 * 根据组件分类获取对应的标签类型
 */
function getComponentTagType(category?: string): string {
  const typeMap: Record<string, string> = {
    'default': 'primary',
    'productivity': 'success',
    'lifestyle': 'warning',
    'information': 'info',
    'data': 'danger',
    'communication': 'danger',
    'task': 'danger'
  }
  return typeMap[category || 'default'] || 'primary'
}
</script>

<style scoped>
.component-store-view {
  padding: 20px;
  background: var(--bg-color);
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--border-color);
}

.header-content {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: var(--text-color);
}

.page-description {
  margin: 0;
  font-size: 16px;
  color: var(--text-color-secondary);
  line-height: 1.5;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 搜索和筛选 */
.filter-section {
  margin-bottom: 30px;
}

/* 统计信息 */
.stats-section {
  margin-bottom: 30px;
}

.stat-card {
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.installed {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.loaded {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon.categories {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-color-secondary);
}

/* 组件列表 */
.components-section {
  margin-bottom: 30px;
}

.loading-container,
.error-container,
.empty-container {
  padding: 60px 0;
  text-align: center;
}

.components-grid {
  display: grid;
  gap: 20px;
}

.component-col {
  margin-bottom: 20px;
}

.component-card {
  height: 100%;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  transition: all 0.3s ease;
}

.component-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.component-card.installed {
  border-color: var(--success-color);
  background: linear-gradient(135deg, rgba(76, 175, 80, 0.05) 0%, rgba(129, 199, 132, 0.05) 100%);
}

.component-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
}

.component-icon {
  flex-shrink: 0;
}

.component-info {
  flex: 1;
  min-width: 0;
}

.component-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.component-version {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: var(--text-color-secondary);
}

.component-category {
  display: inline-block;
}

.component-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.component-description {
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
  color: var(--text-color-secondary);
  flex: 1;
}

.component-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--text-color-secondary);
}

.component-actions {
  margin-top: auto;
}

/* 组件详情 */
.component-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.dependency-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.component-preview {
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  padding: 20px;
  min-height: 300px;
}

.preview-content {
  width: 100%;
  height: 100%;
}

.preview-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 260px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .component-col {
    span: 12;
  }
}

@media (max-width: 768px) {
  .component-store-view {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-section .el-col {
    margin-bottom: 12px;
  }
  
  .stats-section .el-col {
    margin-bottom: 16px;
  }
  
  .component-col {
    span: 24;
  }
  
  .component-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 8px;
  }
  
  .component-stats {
    justify-content: center;
  }
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .component-store-view {
    background: var(--bg-color);
  }
  
  .page-header {
    border-color: var(--border-color);
  }
  
  .stat-card,
  .component-card {
    background: var(--card-bg);
    border-color: var(--border-color);
  }
  
  .component-header {
    border-color: var(--border-color);
  }
  
  .detail-section {
    border-color: var(--border-color);
  }
  
  .component-preview {
    border-color: var(--border-color);
  }
}
</style>
